package com.snail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.service.SysRolePermissionService;
import com.snail.model.pojo.SysRolePermission;
import com.snail.mapper.SysRolePermissionMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Monica
 * @description 针对表【sys_role_permission】的数据库操作Service实现
 * @createDate 2025-07-16 10:22:25
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission>
        implements SysRolePermissionService {

    /**
     * 新增角色权限关系
     *
     * @param roleId        角色ID
     * @param permissionIds 权限ID列表
     */
    @Override
    @Transactional
    public void addPermissionsToRole(Long roleId, List<Long> permissionIds) {
        // 1. 删除旧的权限绑定
        LambdaQueryWrapper<SysRolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRolePermission::getRoleId, roleId);
        this.remove(wrapper);

        // 2. 构建新权限关系并插入
        List<SysRolePermission> list = permissionIds.stream().map(pid -> {
            SysRolePermission rp = new SysRolePermission();
            rp.setRoleId(roleId);
            rp.setPermissionId(pid);
            return rp;
        }).collect(Collectors.toList());

        this.saveBatch(list); // 批量插入
    }

    /**
     * 根据角色ID获取权限ID列表
     */
    public List<Long> getPermissionIdsByRoleId(Long roleId) {
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<SysRolePermission> list = this.list(queryWrapper);

        return list.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
    }

}



